package com.github.androiddevelopmentframework;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

import com.github.freewu.commons.http.HttpFileCallBack;
import com.github.freewu.commons.http.HttpUtils;
import com.github.freewu.commons.utils.ToastUtil;
import com.github.freewu.mvp.presenter.Presenter;
import com.github.freewu.mvp.view.BaseActivity;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;

/**
 * Created by free on 16-10-19.
 */

public class DownLoadFileActivity extends BaseActivity implements View.OnClickListener{

    private ProgressBar progressBar;

    private Button btn;

    @Override
    public int getLayout() {
        return R.layout.activity_download_file;
    }

    @Override
    public void initView(View mView) {
        setTitle("文件下载");

        progressBar=(ProgressBar)mView.findViewById(R.id.progressBar);

        btn=(Button)mView.findViewById(R.id.button);

        btn.setOnClickListener(this);
    }

    @Override
    public void initData() {
    }

    @Override
    public void onClick(View v) {
        File file=new File(ContextCompat.getExternalFilesDirs(getContext(),null)[0],"update.apk");

        HttpUtils.getInstance().downloadFile("http://res5.d.cn/e2418a8a3da6128ab817549feb96a326e6eab031336b7aa816b10654687c3e529922b24f391d6714627ca313a51e32271b92076805cbcb2a298de075dc14cf26.apk?f=web", file, new HttpFileCallBack() {
            @Override
            public void onError(Call call, Exception e) {
                progressBar.setProgress(0);

                ToastUtil.showShort(getContext(),"下载出错"+e.toString());
            }

            @Override
            public void onSuccess(Call call, File downloadPath) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.parse("file://"
                                + downloadPath.getAbsolutePath()),
                        "application/vnd.android.package-archive");
                getActivity().startActivity(intent);
            }

            @Override
            public void onProgress(long progressByte, long allByte) {
                float progress=(float)progressByte/allByte;

                progressBar.setProgress((int)(progress*100));
            }
        });
    }
}
